<template>
  <!-- <view class="container_select_address">
        <nut-cell title="请选择省市区" :desc="address.value.toString()" @click="address.visible = true"></nut-cell>
        <nut-cascader valueKey="name" textKey="name" title="请选择省市区" v-model:visible="address.visible"
            v-model="address.value" @change="change" :options="address.options" :closeable="true"></nut-cascader>
    </view> -->
  <nut-popup position="bottom" v-model:visible="props.show">
    <nut-picker v-if="props.show" v-model="selectedCascader" :columns="cascaderColumns" title="城市选择" @confirm="confirm" @cancel="cancel"></nut-picker>
  </nut-popup>
</template>

<script lang="ts" setup>
import { $post } from "@/@api/index";
import { ref, watch,nextTick } from "vue";
import Taro, { useDidShow,useLoad } from "@tarojs/taro";
export interface AddressList {
  code: string;
  children?: AddressList[];
  id: number;
  name: string;
}

function toDistrictTree(addressList: any) {
  return addressList.map(it => {
    return {
      text: it.name,
      value: it.name,
      children: it.children ? toDistrictTree(it.children) : null
    }
  })
}


const props = defineProps<{
  addressInfo?: string[];
  showonlyTF: string;
  show: boolean;
}>();

const selectedCascader = ref<string[]>(["福建省", "三明市", "梅列区"]);
const cascaderColumns = ref([
  {
    text: "福建省",
    value: "福建省",
    children: [
      {
        text: "三明市",
        value: "三明市",
        children: [
          { text: "梅列区", value: "梅列区" },
        ],
      },
    ],
  },
]);

watch(()=>props.show,(newVal)=>{
  if(newVal){
    getAddress()
  }
},{immediate: true})
watch(()=>props.addressInfo,(newVal)=>{
  selectedCascader.value = JSON.parse(JSON.stringify(newVal))
})

function confirm() {
    console.log(selectedCascader.value[0]);
    emit("selectAddress",selectedCascader.value );
    // Taro.showToast({
    //   title: selectedOptions.map((val: any) => val.text).join(","),
    //   icon: "none",
    // });
}

function cancel() {
  emit('cancelSelectAddress')
}

const emit = defineEmits<{
  (e: "selectAddress", args: string[]): void;
  (e: "cancelSelectAddress"): void;
}>();
// 基础用法
const address = ref<{
  visible: boolean;
  value: string[];
  options: AddressList[];
}>({
  visible: false,
  value: [],
  options: [],
});


async function getAddress() {
  const res = await $post<{ info: AddressList[] }>("http://it.shenghui56.com/serversh/general/addressByCode", {
    showallbranchs: "true",
    showonlyTF: props.showonlyTF,
  });
  //address.value.options = res.data.info
  cascaderColumns.value = toDistrictTree(res.data.info)
  nextTick(()=>{
    selectedCascader.value = ["福建省", "福州市", "鼓楼区"]
  })

}

</script>

<style>
.container_select_address {
  height: 100rpx;
  border-bottom: 1px solid #ccc;
  background-color: #fff;
}
</style>
